package item24;

import org.junit.Assert;
import org.junit.Test;

/**
 * @author Lv Jing
 * @date 2018年07月31日 23:31
 */
public class ReverseList {

    /**
     * 面试题24：反转链表，输出新链表表头
     * 思路：其实这题很简单，主要就是指针的操作，同时在遍历链表的同时就进行反转
     */
    class Solution {
        public ListNode ReverseList(ListNode head) {
            if (head == null) {
                return null;
            }

            ListNode currentNode = head;
            ListNode reverseHead = null;
            ListNode temp = null;
            ListNode pre = null;
            while (currentNode != null) {
                temp = currentNode.next;
                currentNode.next = pre;
                if (temp == null) {
                    reverseHead = currentNode;
                }
                pre = currentNode;
                currentNode = temp;
            }
            return reverseHead;
        }
    }

    public class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    @Test
    public void run01() {
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, null)));
        ListNode reverseHead = new Solution().ReverseList(head);
        Assert.assertEquals(reverseHead.val, 3);
    }
}
